# Import required libraries
import numpy as np
from PIL import Image

# --- Configuration ---
# Text file containing the image data
INPUT_FILE = '111.txt'
# Desired output image filename
OUTPUT_FILE = '111.png'
# --- End of Configuration ---

def convert_text_to_image(input_path, output_path):
    """
    Reads a text file in a specific format and converts it to a grayscale image.
    The file format should be:
    First line: "width,height"
    Subsequent lines: Space-separated pixel values (0-255)
    """
    print("Starting conversion...")
    print(f"Reading file: '{input_path}'")

    try:
        # Open and read all lines from the text file
        with open(input_path, 'r') as f:
            lines = f.readlines()

        # 1. Parse the first line to get the image width and height
        header = lines[0].strip()
        width_str, height_str = header.split(',')
        width, height = int(width_str), int(height_str)
        print(f"Parsed image dimensions: {width}x{height}")

        # 2. Read all pixel data
        all_pixels = []
        # Iterate from the second line onwards
        for line in lines[1:]:
            # Split each line's string by spaces and convert to integers
            pixel_values = [int(p) for p in line.strip().split()]
            # Add to the total pixel list
            all_pixels.extend(pixel_values)

        print(f"Read a total of {len(all_pixels)} pixel values.")

        # 3. Validate if the total number of pixels matches the expected count
        expected_pixels = width * height
        if len(all_pixels) != expected_pixels:
            print(f"Warning: The number of pixels read ({len(all_pixels)}) does not match the expected count ({expected_pixels})!")
            print("Please ensure the data in the input file is complete.")
            # If the pixel count is incorrect, stop execution
            return

        # 4. Create the image
        # Convert the 1D pixel list to a NumPy array with dtype uint8
        image_array = np.array(all_pixels, dtype=np.uint8)
        
        # Reshape the 1D array into a 2D matrix (height x width)
        image_matrix = image_array.reshape((height, width))

        # Create an image object from the 2D matrix using Pillow ('L' mode for 8-bit grayscale)
        img = Image.fromarray(image_matrix, 'L')

        # 5. Save the image
        img.save(output_path)
        print(f"Success! Image has been saved to: '{output_path}'")

    except FileNotFoundError:
        print(f"Error: File '{input_path}' not found. Please make sure it is in the same directory as the script.")
    except Exception as e:
        print(f"An error occurred during processing: {e}")

# --- Run the main function ---
if __name__ == "__main__":
    convert_text_to_image(INPUT_FILE, OUTPUT_FILE)